package com.shortlink.project.service.impl;

import cn.hutool.core.text.StrBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shortlink.project.common.convention.exception.ServiceException;
import com.shortlink.project.dao.entity.ShortLinkDO;
import com.shortlink.project.dao.mapper.ShortLinkMapper;
import com.shortlink.project.dto.req.ShortLinkCreateReqDTO;
import com.shortlink.project.dto.resp.ShortLinkCreateRespDTO;
import com.shortlink.project.service.ShortLinkService;
import com.shortlink.project.toolKit.HashUtil;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.dbdiscovery.mysql.exception.replica.DuplicatePrimaryDataSourceException;
import org.redisson.api.RBloomFilter;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLinkDO> implements ShortLinkService {

    private final RBloomFilter<String> shortUriCreatePenetrationBloomFilter;

    @Override
    public ShortLinkCreateRespDTO create(ShortLinkCreateReqDTO requestParam) {
        String shortLinkSuffix = generateShortUri(requestParam);
//        String fullShortUrl = requestParam.getDomain() + "/" + shortLinkSuffix;
        String fullShortUrl = StrBuilder.create(requestParam.getDomain())
                .append("/")
                .append(shortLinkSuffix)
                .toString();
        ShortLinkDO shortLinkDO = ShortLinkDO.builder()
                .originUrl(requestParam.getOriginUrl())
                .fullShortUrl(fullShortUrl)
                .shortUri(shortLinkSuffix)
                .describe(requestParam.getDescribe())
                .domain(requestParam.getDomain())
                .gid(requestParam.getGid())
                .createdType(requestParam.getCreatedType())
                .enableStatus(0)
                .validDate(requestParam.getValidDate())
                .validDateType(requestParam.getValidDateType())
                .shortUri(shortLinkSuffix)
                .build();
        try{
            baseMapper.insert(shortLinkDO);
        }catch (DuplicatePrimaryDataSourceException e){
            LambdaQueryWrapper<ShortLinkDO> queryWrapper = Wrappers.lambdaQuery(ShortLinkDO.class)
                    .eq(ShortLinkDO::getFullShortUrl, fullShortUrl);
            ShortLinkDO hasShortLink = baseMapper.selectOne(queryWrapper);
            if(hasShortLink != null){
                throw new ServiceException("短链接生成重复");
            }
        }
        shortUriCreatePenetrationBloomFilter.add(fullShortUrl);
        return ShortLinkCreateRespDTO.builder()
                .fullShortUrl(fullShortUrl)
                .originUrl(requestParam.getOriginUrl())
                .gid(requestParam.getGid())
                .build();
    }

    public String generateShortUri(ShortLinkCreateReqDTO requestParam) {
        int tryCount = 0;
        String shortLinkSuffix;
        while (true){
            if(tryCount > 10){
                throw new ServiceException("短链接频繁生成,请稍候重试~");
            }
            String originUrl = requestParam.getOriginUrl();
            originUrl += System.currentTimeMillis();
            shortLinkSuffix = HashUtil.hashToBase62(originUrl);
            if(!shortUriCreatePenetrationBloomFilter.contains(requestParam.getDomain() + "/" + shortLinkSuffix)){
                break;
            }
            tryCount++;
        }
        return shortLinkSuffix;
    }
}
